<template>
  <div class="main main-index">
    <el-card>
      <template #header>数据管理</template>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="标题">
          <el-input v-model="formInline.title" placeholder="标题" clearable />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="formInline.category" placeholder="分类" clearable>
            <el-option v-for="item in categoryList" :label="item.category|| '默认分类'" :value="item.category|| '默认分类'" />
          </el-select>
        </el-form-item>
        <el-form-item label="启用状态">
          <el-select v-model="formInline.status" placeholder="启用状态" clearable>
            <el-option label="未启用" value="0" />
            <el-option label="已启用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="formInline.createTime" type="date" placeholder="请选择" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="fetchLibraries" :icon="Search">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card>
      <div style="margin-bottom: 10px; text-align: right;">
        <el-button type="warning" :icon="Plus" @click="toAdd">
          新增
        </el-button>
      </div>
      <el-table :data="libraries" style="width: 100%" border :row-class-name="tableRowClassName"
        :header-cell-style="{'text-align': 'center','background-color':'#f0f0f0'}">
        <el-table-column prop="Title" label="标题" width="180" />
        <el-table-column prop="Category" label="分类" width="120" />
        <el-table-column prop="Url" label="链接地址">
          <template #default="scope">
            <a :href="scope.row.Url" target="_blank">{{scope.row.Url}}</a>
          </template>
        </el-table-column>
        <el-table-column prop="Img" label="缩略图">
          <template #default="scope">
            <div :style="{background:scope.row.bgColor,padding:'10px'}">
              <img :src="scope.row.Img" :alt="scope.row.Img" style="width: 100px;">
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="Descriptions" label="描述" />
        <el-table-column prop="Status" label="启用状态" width="120" align="center">
          <template #default="scope">
            {{scope.row.Status==1?'已启用':'未启用'}}
          </template>
        </el-table-column>
        <el-table-column prop="CreateTime" label="创建时间" sortable width="210" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.CreateTime)}}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center">
          <template #default="scope">
            <el-button type="text" @click="toEdit(scope.row)">
              编辑
            </el-button>
            <el-button type="text">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <!-- <el-pagination background layout="total, sizes, prev, pager, next, jumper" v-model:current-page="pageIndex"
        v-model:page-size="pageSize" :total="totalPages" @size-change="handleSizeChange"
        @current-change="handleCurrentChange" style="--el-color-primary: #ffc107" /> -->
      <div style="text-align: center; width: 100%;">
        <el-pagination layout="  prev, pager, next" v-model:current-page="pageIndex" v-model:page-size="pageSize"
          :total="totalPages" @size-change="handleSizeChange" @current-change="handleCurrentChange"
          style="--el-color-primary: #e6a23c" />
      </div>
    </el-card>
  </div>
</template>

<script lang="ts" setup>
  import { ref, computed, reactive, onMounted } from 'vue';
  import { ElForm, ElFormItem, ElCard, ElTable, ElTableColumn, ElInput, ElSelect, ElOption, ElDatePicker, ElButton, ElPagination } from 'element-plus'

  import {
    Search,
    Plus
  } from '@element-plus/icons-vue'

  import { getLibraries, getLibrariesCategoryList } from '../../../http/api'; // 假设你的 API 服务文件位于 '@/services/api.js'  
  import { formatDate, momentTimeZone } from '../../../utils/dateUtils';

  import { useRouter } from 'vue-router';

  const router = useRouter();

  interface CategoryForm {
    title?: string; // 如果title是可选的，并且可能是一个字符串  
    category?: string; // 假设category也是一个可选的字符串  
    description?: string; // 同上  
    status?: string | number; // 状态可能是字符串或数字，取决于你的API设计  
    createTime?: Date | string; // 假设创建时间可以是一个Date对象或字符串格式  
  }

  const formInline = reactive < CategoryForm > ({
    // 初始化对象属性（虽然它们是可选的，但在这里我们为示例提供了默认值）  
    title: '',
    category: '',
    description: '',
    status: '', // 或者你可以使用数字，取决于你的API  
    createTime: new Date().toISOString(), // 或者你可以使用字符串格式  
  });

  // 使用 computed 来代替直接定义函数，以便更好地利用 Vue 的响应式系统  
  // @ts-nocheck  
  const tableRowClassName = computed < Number > ((row, rowIndex) => {
    console.log(row)
    if (rowIndex === 1) {
      return 'warning-row';
    } else if (rowIndex === 3) {
      return 'success-row';
    }
    return '';
  });

  interface CategoryData {
    id?: Number;
    title?: string;
    category?: string;
    description?: string;
    content?: string;
    img?: string;
    url?: string;
    status?: string | number;
    createTime?: Date | string | undefined;
  }

  let categoryList = ref < CategoryData[] > ([]);

  //获取列表数据
  let dataSourceList = ref(null);
  let libraries = ref([]); // 存储图书列表的响应式引用  
  let error = ref(null); // 存储错误的响应式引用  
  let pageSize = ref(10);
  let pageIndex = ref(1);
  let totalPages = ref(0); // 存储总页数  

  interface QueryParams {
    // ... 可能还有其他属性  
    pageSize: number;
    pageIndex: number;
    // 可能还有其他的查询参数，比如 title, category 等，如果 formInline 中有这些属性，并且它们也是 QueryParams 的一部分，那么上面的展开运算符就会正常工作  
  }

  const fetchCategoryList = async () => {
    try {
      const params: QueryParams = {
        ...formInline, // 注意：如果 formInline 中有与 QueryParams 冲突的属性，可能需要额外处理  
        pageSize: pageSize.value,
        pageIndex: pageIndex.value
      };

      // @ts-nocheck  
      const response = await getLibrariesCategoryList(params)

      // 假设 response 是一个数组，其中第一个元素是图书列表，第二个元素是包含总页数的对象  
      if (Array.isArray(response) && response.length >= 2 && Array.isArray(response[1]) && typeof response[1][0].total === 'number') {
        categoryList.value = response
        error.value = null;
      } else {
        // 处理响应格式错误的情况  
        categoryList.value = [];
        (error.value as any) = 'Invalid response format.';
      }

    } catch (e) {
      categoryList.value = [];
      if (typeof e === 'object' && e !== null && 'message' in e) {
        (error.value as any) = (e as Error).message;

      }
    }
  }
  // 获取图书列表  
  const fetchLibraries = async () => {
    try {

      const response = await getLibraries({
        ...formInline,
        createTime: formInline.createTime ? momentTimeZone(new Date(formInline.createTime)) : undefined,
        pageSize: pageSize.value,
        pageIndex: pageIndex.value
      });
      // 添加对响应类型的检查  
      if (Array.isArray(response) && response.length >= 2 && Array.isArray(response[1]) && typeof response[1][0].total === 'number') {
        libraries.value = response[0];
        error.value = null;
        totalPages.value = response[1][0].total;
      } else {

        libraries.value = [];
        (error.value as any) = response.msg;
      }
    } catch (e) {
      libraries.value = [];
      if (typeof e === 'object' && e !== null && 'message' in e) {
        (error.value as any) = (e as Error).message;

      }
    }
  };
  // @ts-nocheck  
  const handleSizeChange = (newPage) => {
    pageIndex.value = newPage;
    fetchLibraries(); // 更新页码后重新获取数据  
  }
  // @ts-nocheck  
  const handleCurrentChange = (newPage) => {
    pageIndex.value = newPage;
    fetchLibraries(); // 更新页码后重新获取数据  
  }
  const toAdd = () => {
    router.push('/admin/libraries/create')
  }
  const toEdit = (row) => {
    router.push({
      path: '/admin/libraries/edit/' + row.Id,
    })
  }

  onMounted(() => {
    fetchLibraries();
    fetchCategoryList();
  });

  defineExpose({
    dataSourceList,
    libraries,
    error,
    pageSize,
    pageIndex,
    totalPages,
    fetchLibraries,
    handleSizeChange,
    handleCurrentChange,
    toAdd,
    toEdit,
    fetchCategoryList
  })
</script>

<style scoped>
  .main {
    margin: 20px;
  }


  .demo-form-inline .el-input {
    --el-input-width: 220px;
  }

  .demo-form-inline .el-select {
    --el-select-width: 220px;
  }

  .el-card,
  .el-table {
    margin-bottom: 10px;
  }


  /* 使用自定义的 CSS 变量名称，以避免潜在的命名冲突 */
  .warning-row {
    --custom-table-tr-bg-color: var(--el-color-warning-light-9);
    background-color: var(--custom-table-tr-bg-color);
  }

  .success-row {
    --custom-table-tr-bg-color: var(--el-color-success-light-9);
    background-color: var(--custom-table-tr-bg-color);
  }

  :root {
    color-scheme: light;
    --el-color-primary: #409eff;
    --el-color-primary-light-3: #79bbff;
    --el-color-primary-light-5: #a0cfff;
    --el-color-primary-light-7: #c6e2ff;
    --el-color-primary-light-8: #d9ecff;
    --el-color-primary-light-9: #ecf5ff;
    --el-color-primary-dark-2: #337ecc;
    --el-color-success: #67c23a;
    --el-color-success-light-3: #95d475;
    --el-color-success-light-5: #b3e19d;
    --el-color-success-light-7: #d1edc4;
    --el-color-success-light-8: #e1f3d8;
    --el-color-success-light-9: #f0f9eb;
    --el-color-success-dark-2: #529b2e;
    --el-color-warning: #e6a23c;
    --el-color-warning-light-3: #eebe77;
    --el-color-warning-light-5: #f3d19e;
    --el-color-warning-light-7: #f8e3c5;
    --el-color-warning-light-8: #faecd8;
    --el-color-warning-light-9: #fdf6ec;
    --el-color-warning-dark-2: #b88230;
    --el-color-danger: #f56c6c;
    --el-color-danger-light-3: #f89898;
    --el-color-danger-light-5: #fab6b6;
    --el-color-danger-light-7: #fcd3d3;
    --el-color-danger-light-8: #fde2e2;
    --el-color-danger-light-9: #fef0f0;
    --el-color-danger-dark-2: #c45656;
    --el-color-error: #f56c6c;
    --el-color-error-light-3: #f89898;
    --el-color-error-light-5: #fab6b6;
    --el-color-error-light-7: #fcd3d3;
    --el-color-error-light-8: #fde2e2;
    --el-color-error-light-9: #fef0f0;
    --el-color-error-dark-2: #c45656;
    --el-color-info: #909399;
    --el-color-info-light-3: #b1b3b8;
    --el-color-info-light-5: #c8c9cc;
    --el-color-info-light-7: #dedfe0;
    --el-color-info-light-8: #e9e9eb;
    --el-color-info-light-9: #f4f4f5;
    --el-color-info-dark-2: #73767a;
    --el-bg-color: #ffffff;
    --el-bg-color-page: #f2f3f5;
    --el-bg-color-overlay: #ffffff;
    --el-text-color-primary: #303133;
    --el-text-color-regular: #606266;
    --el-text-color-secondary: #909399;
    --el-text-color-placeholder: #a8abb2;
    --el-text-color-disabled: #c0c4cc;
    --el-border-color: #dcdfe6;
    --el-border-color-light: #e4e7ed;
    --el-border-color-lighter: #ebeef5;
    --el-border-color-extra-light: #f2f6fc;
    --el-border-color-dark: #d4d7de;
    --el-border-color-darker: #cdd0d6;
    --el-fill-color: #f0f2f5;
    --el-fill-color-light: #f5f7fa;
    --el-fill-color-lighter: #fafafa;
    --el-fill-color-extra-light: #fafcff;
    --el-fill-color-dark: #ebedf0;
    --el-fill-color-darker: #e6e8eb;
    --el-fill-color-blank: #ffffff;
    --el-box-shadow: 0px 12px 32px 4px rgba(0, 0, 0, .04), 0px 8px 20px rgba(0, 0, 0, .08);
    --el-box-shadow-light: 0px 0px 12px rgba(0, 0, 0, .12);
    --el-box-shadow-lighter: 0px 0px 6px rgba(0, 0, 0, .12);
    --el-box-shadow-dark: 0px 16px 48px 16px rgba(0, 0, 0, .08), 0px 12px 32px rgba(0, 0, 0, .12), 0px 8px 16px -8px rgba(0, 0, 0, .16);
    --el-disabled-bg-color: var(--el-fill-color-light);
    --el-disabled-text-color: var(--el-text-color-placeholder);
    --el-disabled-border-color: var(--el-border-color-light);
    --el-overlay-color: rgba(0, 0, 0, .8);
    --el-overlay-color-light: rgba(0, 0, 0, .7);
    --el-overlay-color-lighter: rgba(0, 0, 0, .5);
    --el-mask-color: rgba(255, 255, 255, .9);
    --el-mask-color-extra-light: rgba(255, 255, 255, .3);
    --el-border-width: 1px;
    --el-border-style: solid;
    --el-border-color-hover: var(--el-text-color-disabled);
    --el-border: var(--el-border-width) var(--el-border-style) var(--el-border-color);
    --el-svg-monochrome-grey: var(--el-border-color);
  }
</style>
<style>
  .main-index label {
    margin-bottom: 0 !important;
  }
</style>